package com.leetcode.bfs_dfs;

import com.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Leetcode104 {

    /** solution 1：
     * 参考 Leetcode102,广度优先搜索
     */
    /*
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int level = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            level++;
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode curr = queue.poll();
                if (curr.left != null) {
                    queue.offer(curr.left);
                }

                if (curr.right != null) {
                    queue.offer(curr.right);
                }
            }
        }

        return level;
    }
*/

    /** solution 2: 深度优先搜索
     * 采用递归的方法，左子树遍历返回其深度，右子树遍历并放回器深度，最后的比较哪个深度最大
     * 递归计算的时候，最后的叶子节点必然返回0，然后逐级返回再加1，0..1..2..n
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left,right)+1;
    }
    /**
     * 测试程序
     * 3
     * / \
     * 9  20
     * /  \
     * 15   7
     *
     * @param args
     */
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20);
        root.left = left;
        root.right = right;
        TreeNode rleft = new TreeNode(15);
        TreeNode rright = new TreeNode(7);
        right.left = rleft;
        right.right = rright;

        Leetcode104 leetcode104 = new Leetcode104();
        System.out.println(leetcode104.maxDepth(root));
    }
}
